package com.distribute.framework.core.sql.mongodb;

import com.distribute.framework.core.web.helper.Utils;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;


public class MongodbDataSource {
	
	String address;
	String database; 
	
	public MongodbDataSource() {
	}
	/**
	 * @param address
	 * @param username
	 * @param password
	 */
	public MongodbDataSource(String address) {
		super();
		this.address = address;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	
	
	MongoClient mongo;
	@SuppressWarnings("deprecation")
	public Mongo getMongo() {
		if(mongo!=null)
			return mongo;
		while(mongo==null){
			MongoClientOptions.Builder options = MongoClientOptions.builder();
			options.socketKeepAlive(true);
			MongoClientURI connectionString = new MongoClientURI(this.getAddress());
			mongo = new MongoClient(connectionString);
			Matcher matcher = Pattern.compile("mongodb://[^/]+/([^\\?]+)").matcher(this.address);
			matcher.find();
			this.database = matcher.group(1);
			return mongo;
		}
		return mongo;
	}
	
	public DB getDb() {
		DB db = getMongo().getDB(this.getDatabase());
		return db;
	}
	
	public DBCollection getCollection(String name){
		return getDb().getCollection(name);
	}
	
	public <T> MongodbDaoSupport<T> getDao(final Class<T> modelClass){
		return new MongodbDaoSupport(this){
			@Override
			public Class getTClass() {
				return modelClass;
			}
			@Override
			public Map getTIndex() {
				return new HashMap();
			}
		};		
	}
	
	public static void close(){
		
	}
	
	static Map<String,MongodbDataSource> dataSources = new HashMap();
	public static MongodbDataSource getMongodbDataSource(String name){
		MongodbDataSource mongodbDataSource = null;
		if((mongodbDataSource = dataSources.get(name))!=null){
			return mongodbDataSource;
		}
		if(Utils.empty(Utils.config(name+".address"))){
			throw new RuntimeException("无法在application.properties文件中找到"+name+".address");
		}
		mongodbDataSource = new MongodbDataSource(Utils.config(name+".address"));
		mongodbDataSource.getMongo();
		return mongodbDataSource;
	}
	public String getDatabase() {
		return database;
	}
	public void setDatabase(String database) {
		this.database = database;
	}

}